﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml; 
using System.Resources;
using System.Configuration;

using YT.DB;
using YT.Commons;
using System.Runtime.InteropServices;
using System.Data.SqlClient;

namespace YT_XHProject
{
    public partial class frmLogin : Form
    {
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

        [DllImport("kernel32")]
        private static extern int WritePrivateProfileString(string section, string key, string Text, string filePath);

        [DllImport("kernel32")]
        private static extern int GetPrivateProfileSection(string section, [MarshalAs(UnmanagedType.LPArray)] byte[] ReturnedString, int nSize, string FileName);

        [DllImport("Advapi32.dll", EntryPoint = "GetUserName", ExactSpelling = false, SetLastError = true)]
        static extern bool GetUserName([MarshalAs(UnmanagedType.LPArray)] byte[] lpBuffer, [MarshalAs(UnmanagedType.LPArray)] Int32[] nSize);

        private string mstrReadLogFile = Application.StartupPath + "\\option.ini";
        public frmLogin()
        {
            InitializeComponent();
            
        }

        private bool blnIsNose()
        {
            const string ISNOSE="ISNOSE";
            FileStream fs = new FileStream( Application.StartupPath  + "\\AppConfing.txt", FileMode.Open, FileAccess.Read);
            StreamReader sw = new StreamReader(fs, System.Text.Encoding.GetEncoding("GB2312"));
            string strIsNose=string.Empty ;
            sw.BaseStream.Seek(0, SeekOrigin.Begin);
            string line = sw.ReadLine();
            while (line != null)
            {
                strIsNose= line;
                line = sw.ReadLine();
            }
            if ( strIsNose.Trim().ToUpper() == ISNOSE )
            {
                SysVar.IsNose = true ;                
            }
            else 
            {
                SysVar.IsNose =false ;
            }
            sw.Close();
            return true;
        }
        
        private void initText()
        {
            Properties.Settings config = Properties.Settings.Default;
            if (config.UserName == "")
                txtLoginName.Text = GetWinUserName();
            else
                txtLoginName.Text = config.UserName;

            txtPassword.Text = "";
            txtDBPassword.Text = config.Password; 
            txtServerName.Text = config.ServerName;
            txtDBName.Text = config.DBName;
            txtDBPassword.Text = config.Password;

            if (blnIsNose() == true)
            {
                if (SysVar.IsNose == true)
                {
                    label6.Text = "         变应性鼻炎规范化治疗                    ";
                    label7.Text = "湖北省过敏性协作组 数据平台系统";                    
                }
            }
            else
            {

            }
            if (txtServerName.Text.TrimEnd() == "")
            {
                txtServerName.Text = ".";
            }
            lblSystemInfo.Text = "";
        }

        private bool  initHospital()
        {
            
            DBAccess dbcon = new DBAccess(false, false);
            string strSQL = string.Empty;
            strSQL = "select * from mHospital where IsCurHospital=1";
            DataRow drRow = dbcon.GetDataFirstRow(strSQL);
            if (drRow != null) return true ;
            lblSystemInfo.Text = "正在初始化医院和用户......";
            frmInputCode frmCode = new frmInputCode();
            string strUserName=txtLoginName.Text;
            if (!frmCode.ShowForm(ref strUserName))
            {
                this.Cursor = Cursors.Default;
                return false;
            }
            txtLoginName.Text = strUserName;

            //FileStream fs = new FileStream(Application.StartupPath + "\\HospitalName.txt", FileMode.Open, FileAccess.Read);
            //StreamReader sw = new StreamReader(fs, System.Text.Encoding.GetEncoding("GB2312"));
            //string strHospitalID = string.Empty;
            //sw.BaseStream.Seek(0, SeekOrigin.Begin);
            //string line = sw.ReadLine();
            //while (line != null)
            //{
            //    strHospitalID = line;
            //    line = sw.ReadLine();
            //}
            //if (strHospitalID.Trim().ToUpper() =="")
            //{
            //    return;
            //}
            //else
            //{                
            //    strSQL = "update mHospital set IsCurHospital=1 where HospitalID='" + strHospitalID + "'";
            //    dbcon.ExecuteSql(strSQL);                
            //}

            //strSQL = "select * from mUser";
            //drRow = dbcon.GetDataFirstRow(strSQL);
            //if (drRow == null)  // 如果没有USER就要用默认的user
            //{
            //    string strGrpNo = string.Empty ;
            //    strSQL = "INSERT INTO muser( UserNo, UserName, GroupNo, PassWord, isAdmin )" +
            //             "VALUES ('"+ strHospitalID +"','"+ strHospitalID +"','"+ strGrpNo +"','"+ strHospitalID +"','0')   ";
            //    dbcon.ExecuteSql(strSQL);
            //}

            //sw.Close();            
            dbcon.CloseCon();
            return true;

        }

        private bool initDB(string strUserDftServer, string strPassWord, bool blnTrusted)
        {

            if (!File.Exists(Application.StartupPath + "\\WTUnion")) return false;

            string strDBName = "Master";
            string strConnectionPara = string.Empty;
            //if ( strConnectionPara =="" )
            //    strConnectionPara = "data source=.;database=" + strDBName + ";Connect Timeout=90;";            
            //else 
                strConnectionPara = "data source=" + strUserDftServer + ";database=" + strDBName + ";Connect Timeout=90;";            
            if　( !blnTrusted )
                DBAccess.ConnectionDBString = strConnectionPara + "uid=sa;pwd=" + strPassWord;
            else
                DBAccess.ConnectionDBString = strConnectionPara + "Trusted_Connection=yes;";

            DBAccess dBAccess = new DBAccess(false, false);

            
            string strBackUpDBName = "WTUnion";
            string strSQL = string.Empty;
            try
            {
                this.Cursor = Cursors.WaitCursor;
                strSQL = "select * from sysdatabases where name='WTUnion' ";
                DataRow drRow = dBAccess.GetDataFirstRow(strSQL);
                if (drRow == null)   // 如果没有找到， 就要恢复数据库。
                {
                    lblSystemInfo.Text = "正在恢复数据库......";
                    strSQL = " USE master " +
                             " RESTORE FILELISTONLY " +
                             " FROM DISK = '" + Application.StartupPath + "\\WTUnion'" +
                             "   RESTORE DATABASE WTUnion "+
                             "   FROM DISK = '" + Application.StartupPath + "\\WTUnion'" +
                             "   WITH MOVE 'WTUnion_Data' TO '" + Application.StartupPath + "\\WTUnion.mdf', " +
                             "   MOVE 'WTUnion_Log' TO '" + Application.StartupPath + "\\WTUnion_log.ldf'";
                    SqlCommand dbcom = new SqlCommand();
                    SqlConnection dbcon = new SqlConnection(DBAccess.ConnectionDBString);
                    dbcon.Open();
                    dbcom.Connection = dbcon;
                    dbcom.CommandType = CommandType.Text;
                    dbcom.CommandText = strSQL;
                    dbcom.ExecuteNonQuery(); 
                }                
            }
            catch (Exception ex)
            {
                this.Cursor = Cursors.WaitCursor;
                return false; 
            }
            this.Cursor = Cursors.WaitCursor;
            return true;
        }

        public string GetWinUserName()
        {
            string strWinUserName;
            byte[] str = new byte[256];
            Int32[] len = new Int32[1];
            len[0] = 256;
            GetUserName(str, len);

            if (len[0] > 0)
            {
                strWinUserName = System.Text.Encoding.ASCII.GetString(str);
                strWinUserName = strWinUserName.Substring(0, len[0] - 1);
            }
            else
                strWinUserName = "";

            return strWinUserName;
        }

        private void ubtLogin_Click(object sender, EventArgs e)
        {
            
            frmMainMenu FrmMain = new frmMainMenu();
            FrmMain.Opacity = 0;
            Properties.Settings config= Properties.Settings.Default;
            string strUserDftServer = txtServerName.Text;
            string strPassWord = txtDBPassword.Text;
            string strDBName = txtDBName.Text;  

            if (strUserDftServer.Trim() == "")
            {
                MessageBox.Show("请设置数据库服务器的名称。", "", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }
            bool blnIsTrusted = true;
            if (!initDB(strUserDftServer, strPassWord,blnIsTrusted ))
            {
                MessageBox.Show("数据库错误！", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return ;
            }
            lblSystemInfo.Text = "正在连接数据库......";
            string strConnectionPara = "data source=" + strUserDftServer + ";database="+ strDBName +";Connect Timeout=90;";
            if (blnIsTrusted)
                DBAccess.ConnectionDBString = strConnectionPara + "Trusted_Connection=yes;";
            else
                DBAccess.ConnectionDBString = strConnectionPara + "uid=sa;pwd=" + strPassWord ;

            DBAccess dBAccess = new DBAccess(false, false);
            lblSystemInfo.Text = "正在初始化系统......";
           
            #region init system
            SysVar.UserName = this.txtLoginName.Text;
            SysVar.DatabaseName = txtDBName.Text;
            SysVar.ServerName = strUserDftServer ;
            SysVar.CustomerName = BaseFunctions.GetCurrentCusomterName();
            SysVar.Password = txtPassword.Text;
            SysVar.mfrmMdiPar = FrmMain;
            SysVar.HospitalID = DataFunctions.GetFieldValue("mHospital", "HospitalID", "IsCurHospital=1");
            SysVar.HospitalName = DataFunctions.GetFieldValue("mHospital", "HospitalName", "IsCurHospital=1");
            #endregion
            if (!initHospital()) return;
            if (!vaildUser()) return;
            #region init system
            SysVar.UserName = this.txtLoginName.Text;
            SysVar.DatabaseName = txtDBName.Text;
            SysVar.ServerName = strUserDftServer;
            SysVar.CustomerName = BaseFunctions.GetCurrentCusomterName();
            SysVar.Password = txtPassword.Text;
            SysVar.mfrmMdiPar = FrmMain;
            SysVar.HospitalID = DataFunctions.GetFieldValue("mHospital", "HospitalID", "IsCurHospital=1");
            SysVar.HospitalName = DataFunctions.GetFieldValue("mHospital", "HospitalName", "IsCurHospital=1");
            #endregion

            #region save the App.config

            XmlDocument xmldoc = new XmlDocument();
            string strFieldName= System.AppDomain.CurrentDomain.SetupInformation.ConfigurationFile   ;
            xmldoc.Load(strFieldName);            
            xmldoc = new XmlDocument();
            xmldoc.Load(strFieldName);
            XmlNode oNode1 = xmldoc.SelectSingleNode("//configuration//applicationSettings//YT_XHProject.Properties.Settings//setting[@name='UserName']");
            if (oNode1!= null)
            {
                oNode1.InnerText = txtLoginName.Text;
                oNode1.InnerXml = "<value>" + txtLoginName.Text + "</value>";
            }
            oNode1 = xmldoc.SelectSingleNode("//configuration//applicationSettings//YT_XHProject.Properties.Settings//setting[@name='ServerName']");
            if (oNode1 != null)
            {
                oNode1.InnerText = txtServerName.Text;
                oNode1.InnerXml = "<value>" + txtServerName.Text + "</value>";
            }
            oNode1 = xmldoc.SelectSingleNode("//configuration//applicationSettings//YT_XHProject.Properties.Settings//setting[@name='Password']");
            if (oNode1 != null)
            {
                oNode1.InnerText = txtDBPassword.Text;
                oNode1.InnerXml = "<value>" + txtDBPassword.Text + "</value>";
            }
            oNode1 = xmldoc.SelectSingleNode("//configuration//applicationSettings//YT_XHProject.Properties.Settings//setting[@name='DBName']");
            if (oNode1 != null)
            {
                oNode1.InnerText = txtDBName.Text;
                oNode1.InnerXml = "<value>" + txtDBName.Text + "</value>";
            }
            xmldoc.Save(strFieldName);

            #endregion
            //初始化菜单
            string strSQL = "update mMenu set permit04=1 where menuid='400500273000000'";
            dBAccess.ExecuteSql(strSQL);

            strSQL = "update mTableDict set SQLList='select RecID,0 as 序号, SickID, HospitalName,SickName,ID,Sex,  Address, Postal,Phone,curoperation from mSickPerson order by recid desc' where TableName='mSickPerson' and SQLList!='select RecID,0 as 序号, SickID, HospitalName,SickName,ID,Sex,  Address, Postal,Phone,curoperation from mSickPerson order by recid desc'";
            dBAccess.ExecuteSql(strSQL);
            //
            strSQL = "select a.name from [dbo].syscolumns  a  inner join  [dbo].sysobjects b on a.id=b.id where b.name='msickperson' and a.name='NeedMsg'";
            DataRow drCheck = dBAccess.GetDataFirstRow(strSQL);
            if (drCheck == null)
            {

                strSQL = @" ALTER TABLE dbo.mSickperson ADD
                            NeedMsg bit NOT NULL CONSTRAINT DF_mSickperson_NeedMsg DEFAULT 0
                            ";
                dBAccess.ExecuteSql(strSQL); 
            }

            strSQL = "select a.name from [dbo].syscolumns  a  inner join  [dbo].sysobjects b on a.id=b.id where b.name='mOutputHistory' and a.name='FromDate'";
            drCheck = dBAccess.GetDataFirstRow(strSQL);
            if (drCheck == null)
            {

                strSQL = @" ALTER TABLE dbo.mOutputHistory ADD
	                        FromDate datetime NULL,
	                        ToDate datetime NULL
                            ";
                dBAccess.ExecuteSql(strSQL);
            }

            //
            InitOutPutTableName(dBAccess); 
            //
            dBAccess.CloseCon();
            FrmMain.WindowState   = FormWindowState.Maximized;   
            FrmMain.Show();
            lblSystemInfo.Text = "登陆完成.";
            this.Hide();
            this.Left = -10000;
            Cursor.Current = Cursors.Default; 
        }


        private void InitOutPutTableName( DBAccess dbcon )
        {
            string strSQL ="";
            strSQL = "select count(*) from moutputtablename";
            DataRow drRow = dbcon.GetDataFirstRow(strSQL);
            if (drRow != null)
            {
                //if (CvtFunc.ToDouble(drRow[0]) < 40)
                //{
                    dbcon.ExecuteSql("delete from moutputtablename");
                //}
            }
            strSQL = @" insert into moutputtablename ( TableName) values ('EffectAfterTreateHdr');
                        insert into moutputtablename ( TableName) values ('EffectAfterTreateResult');
                        insert into moutputtablename ( TableName) values ('ExamBeforeTreatHdr');
                        insert into moutputtablename ( TableName) values ('ExamBeforTreatResult');
                        insert into moutputtablename ( TableName) values ('JocobsonHdr');
                        insert into moutputtablename ( TableName) values ('JocobsonResult');
                        insert into moutputtablename ( TableName) values ('mContraindication');
                        insert into moutputtablename ( TableName) values ('mContraindicationDetail');
                        insert into moutputtablename ( TableName) values ('mOutputTableName');
                        insert into moutputtablename ( TableName) values ('mOutputHistory');
                        insert into moutputtablename ( TableName) values ('mSickperson');
                        insert into moutputtablename ( TableName) values ('mSickTreatLog');
                        insert into moutputtablename ( TableName) values ('mTreatHistory');
                        insert into moutputtablename ( TableName) values ('NoseCAPExamDetail');
                        insert into moutputtablename ( TableName) values ('NoseCAPExamHdr');
                        insert into moutputtablename ( TableName) values ('NoseDrTreatHistoryDtl');
                        insert into moutputtablename ( TableName) values ('NoseLabExamDtl');
                        insert into moutputtablename ( TableName) values ('NoseLabExamHdr');
                        insert into moutputtablename ( TableName) values ('NoseNormalVisitRecordDtl');
                        insert into moutputtablename ( TableName) values ('NoseSkinPrickTestDetail');
                        insert into moutputtablename ( TableName) values ('NoseSkinPrickTestHdr');
                        insert into moutputtablename ( TableName) values ('NoseTreatmentHistoryDtl');
                        insert into moutputtablename ( TableName) values ('NoseVisitRecordDtl');
                        insert into moutputtablename ( TableName) values ('NoseVisitWeek');
                        insert into moutputtablename ( TableName) values ('NoseVisitWeek_Add');
                        insert into moutputtablename ( TableName) values ('SmsInbox');
                        insert into moutputtablename ( TableName) values ('SmsOutBox');
                        insert into moutputtablename ( TableName) values ('THIResult');
                        insert into moutputtablename ( TableName) values ('titleDtl');
                        insert into moutputtablename ( TableName) values ('titlehdr');
                        insert into moutputtablename ( TableName) values ('titleResult');
                        insert into moutputtablename ( TableName) values ('TreatmentEffectHdr');
                        insert into moutputtablename ( TableName) values ('TreatmentEffectHdr_Emergency');
                        insert into moutputtablename ( TableName) values ('TreatmentEffectHdr_Sure');
                        insert into moutputtablename ( TableName) values ('TreatmentEffectHdr_Watch');
                        insert into moutputtablename ( TableName) values ('TreatmentEffectResult');
                        insert into moutputtablename ( TableName) values ('TreatmentEffectResult_Emergency');
                        insert into moutputtablename ( TableName) values ('TreatmentEffectResult_Sure');
                        insert into moutputtablename ( TableName) values ('TreatmentEffectResult_Watch');
                        insert into moutputtablename ( TableName) values ('UntowardEffectResult')";
            dbcon.ExecuteSql(strSQL);
            return ;
        }

        private bool vaildUser()
        {
            DBAccess dbcon = new DBAccess(false, false);
            string strSQL = string.Empty;
            string strErrMsg = string.Empty;

            strSQL = "select * from mUser where userno='"+ SysVar.UserName   +"'  ";
            DataRow drRow = dbcon.GetDataFirstRow(strSQL);
            if (drRow != null)
            {
                if ( CvtFunc.ToString ( drRow ["Password"]) != SysVar.Password )
                    strErrMsg ="用戶名或密码错误.";               
            }
            else
            {
                strErrMsg = "用戶名或密码错误.";                
            }
            if (strErrMsg == "")
                return true;
            else
            {
                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
        }
              
        public bool GetFile(string strFileName)
        {
            bool bGetFile = false;
            if (strFileName == null) strFileName = "";
            if (File.Exists(strFileName))
            {
                bGetFile = true;
            }
            else
            {
                int iDirIndex = strFileName.IndexOf("/", 0);
                if (iDirIndex != -1)
                {
                    string strDir = strFileName.Substring(0, iDirIndex);
                    if (!Directory.Exists(strDir))
                    {
                        Directory.CreateDirectory(strDir);
                    }
                }
            }
            return bGetFile;
        }

        public void CreateLogFile(string FileName)
        {
            StreamWriter writer = new StreamWriter(FileName, true);
            string strIni = "";
            strIni = "[LastLogin]" + "\r\n";
            strIni += "ServerTotal=0" + "\r\n";
            strIni += "DatabaseTotal=0" + "\r\n" + "\r\n";
            strIni += "[Server]" + "\r\n";
            strIni += "[Database]" + "\r\n";
            strIni += "[Show]" + "\r\n";
            strIni += "FirstShow=frmMain" + "\r\n";
            strIni += "MtnStartTabPage=0" + "\r\n" + "\r\n";
            strIni += "[Exit]" + "\r\n";
            strIni += "Ask=Y" + "\r\n";
            strIni += "ExitTo=Windows" + "\r\n" + "\r\n";
            strIni = strIni + "[View]" + "\r\n";
            strIni = strIni + "Switch=Y" + "\r\n";
            strIni = strIni + "Toolbar=Y" + "\r\n" + "\r\n";
            strIni = strIni + "[LastMenu]" + "\r\n";
            strIni = strIni + "MenuID=";
            writer.WriteLine(strIni);
            writer.Close();

        }

        public string GetInIString(string Section, string Key, string FileName)
        {
            int i;
            StringBuilder sbReturn = new StringBuilder(255);
            string GetInIString = "";

            if (FileName == "") return "";
            if (!GetFile(FileName))
            {
                GetInIString = "";
            }
            else
            {
                i = GetPrivateProfileString(Section, Key, "", sbReturn, 255, FileName);
                if (i > 0)
                {
                    string strReturn = sbReturn.ToString();
                    strReturn = strReturn.Substring(0, i);
                    GetInIString = strReturn.Trim();
                }
                else
                    GetInIString = "";
            }
            return GetInIString;

        }

        public int WriteIniString(string Section, string Key, string strText, string FileName)
        {
            int i;
            int intWriteIniString = 0;

            if (FileName != "")
            {
                if (!GetFile(FileName))
                    intWriteIniString = 0;
                else
                {
                    i = WritePrivateProfileString(Section, Key, strText, FileName);
                    intWriteIniString = i;
                }

            }
            return intWriteIniString;
        }

        public string GetInISection(string Section, string FileName)
        {
            int i;
            string strGetInISection = "";
            byte[] str = new byte[1000];
            if (FileName != "")
            {
                if (!GetFile(FileName))
                    strGetInISection = "";
                else
                {
                    i = GetPrivateProfileSection(Section, str, 1000, FileName);
                    if (i > 0)
                    {
                        strGetInISection = System.Text.Encoding.ASCII.GetString(str);
                        strGetInISection = strGetInISection.Substring(0, i);
                    }
                    else
                        strGetInISection = "";
                }
            }

            return strGetInISection;
        }

        private void frmLogin_Load(object sender, EventArgs e)
        {
            initText();
            timer1.Start();
        }

        private void btnCanel_Click(object sender, EventArgs e)
        {
            this.Close();
            Application.Exit();
        }

        private void btnOption_Click(object sender, EventArgs e)
        {
            if (!pnlSetting.Visible )
            {                
                pnlSetting.Visible = true;
                this.btnOption.Text = this.btnOption.Text.Replace(">>", "<<");
            }
            else
            {                
                pnlSetting.Visible = false;
                this.btnOption.Text = this.btnOption.Text.Replace("<<", ">>");
            }            
        }
        
        private void SelectNextControl( object sender,EventArgs e)
        {
            SelectNextControl(((Control)sender ),true,true,true,false );  
        }

        private void button1_Click(object sender, EventArgs e)
        {
           
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            ChangeOpacity();
        }
        private void ChangeOpacity()
        {

            if (this.Opacity >= 1)
                timer1.Stop();
            this.Opacity += 0.04;

        }

       
    }
}
